package com.isias.system.Controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isias.common.result.Result;
import com.isias.model.El.ElQu;
import com.isias.model.vo.ElQuQueryVo;
import com.isias.system.Config.WenJianConfig;
import com.isias.system.service.ElQuService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping(value="/admin/el/qu")
public class ElQuController {
    @Autowired
    private ElQuService elQuService;


    /**
     * 分页查询(有题库)
     */
    Page<ElQu> pageparam = new Page<>();
    @GetMapping("/{page}/{limit}")
    public Result SeletePage(@PathVariable Integer page, @PathVariable Integer limit, ElQuQueryVo elQuQueryVo){
        pageparam.setCurrent(page);
        pageparam.setSize(limit);
        IPage<ElQu> iPage = elQuService.SeletePage(pageparam,elQuQueryVo);
        return Result.ok(iPage);
    }

    /**
     *获取全部的题目
     */
    @GetMapping
    public Result SeleteAll(ElQuQueryVo elQuQueryVo){
        List<ElQu> elQus = elQuService.SeleteAll(elQuQueryVo);
        return Result.ok(elQus);
    }


    /**
     * 查询单个（用于数据回显）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result GetById(@PathVariable String id){
        ElQu elQu = elQuService.getById(id);
        return Result.ok(elQu);
    }

    /**
     * 添加题
     * @param elQu
     * @return
     */
    @PostMapping
    public Result Add(@RequestBody ElQu elQu){
        if (elQuService.save(elQu)){
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 把某个题目添加到题库里
     * @param repoId
     * @param quId
     * @return
     */
    @GetMapping("/AddQuToRepo/{repoId}/{quId}")
    public Result AddQuToRepo(@PathVariable String repoId,@PathVariable String quId){
        if (elQuService.AddQuToRepo(repoId,quId)){
            return Result.ok();
        }
        return Result.fail("题库中已存在或系统异常");
    }

    /**
     * 修改单个
     * @param ElQu
     * @return
     */
    @PutMapping
    public Result Update(@RequestBody ElQu ElQu){
        if (elQuService.updateById(ElQu)){
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 删除单个
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result DeleteById(@PathVariable String id){
        if (elQuService.removeById(id)){
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 从题库中删除某个题目
     * @param repoId,quId
     * @return
     */
    @DeleteMapping("/DeleteQuToRepo/{repoId}/{quId}")
    public Result DeleteQuToRepo(@PathVariable String repoId,@PathVariable String quId){
        if (elQuService.DeleteQuToRepo(repoId,quId)){
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 根据id列表删除
     */
    @DeleteMapping("/batchRemove")
    public Result batchRemove(@RequestBody List<Long> idList) {
        if (elQuService.removeByIds(idList)) {
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    /**
     * 从题库中根据id列表删除
     */
    @DeleteMapping("/batchRemove/{repoId}")
    public Result DeleteQusToRepo(@PathVariable String repoId,@RequestBody List<String> idList) {
        if (elQuService.DeleteQusToRepo(repoId,idList)) {
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    @GetMapping("/GetRepoAndId")
    public Result GetRepoAndId(){   //获取所有题库名字和id
        return Result.ok(elQuService.GetRepoAndId());
    }

    /**
     * 某些题目可能有图片，可以用此进行上传图片
     * @param file
     * @return
     */
    @PostMapping("/uploadImg")
    public Result<Map<String, Object>> avatar(MultipartFile file) throws IOException {
        // 文件名称  时间日期+文件名_uuid+后缀
        String fileName = StrUtil.format("{}/{}_{}.{}", DateUtil.format(DateUtil.date(), "yyy/MM/dd"), FilenameUtils.getBaseName(file.getOriginalFilename()), DateUtil.format(new Date(), "yyyyMMdd") + IdUtil.fastUUID(), FilenameUtils.getExtension(file.getOriginalFilename()));
        // 父目录
        String baseDir = WenJianConfig.getQuPicturePath();
        //路径拼接
        File desc = new File(baseDir + File.separator + fileName);
        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        // 下载
        file.transferTo(desc);
        int dirLastIndex = WenJianConfig.getProfile().length() + 1;
        // 截取upload/下的名称存入数据库
        String currentDir = baseDir.substring(dirLastIndex);
        String avatar = WenJianConfig.getUrl() + currentDir + "/" + fileName;
        Map<String, Object> map = new HashMap<>();
        // 将头像路径返回，这里是为了头像上传后有一个回显的效果
        map.put("imgUrl", avatar);
        return Result.ok(map);
    }

}
